/**
 * @file imageEncoder.h
 * @author SDK_TEAM
 * @brief
 * @version 0.1
 * @date 2022-11-09
 *
 * Copyright:
 * © 2018 北京灵汐科技有限公司 版权所有。
 * 注意：以下内容均为北京灵汐科技有限公司原创，未经本公司允许，不得转载，否则将视为侵权；对于不遵守此声明或者其他违法使用以下内容者，本公司依法保留追究权。
 * © 2018 Lynxi Technologies Co., Ltd. All rights reserved.
 * NOTICE: All information contained here is, and remains the property of Lynxi.
 * This file can not be copied or distributed without the permission of Lynxi
 * Technologies Co., Ltd.
 *
 */
#pragma once

#include <lyn_api.h>
#include <fstream>
#include <iostream>
#include <string>
#include "util.hpp"

// 图像编码类
class ImageEncoder {
 public:
  ImageEncoder() {}

  void EncodeImageAndSave(lynStream_t stream, const std::string &outputPath,
                          lynCodecBuf_t &image, lynImageInfo_t &imgInfo) {
    lynJencInfo_t encodeAttr;
    encodeAttr.params.height = imgInfo.output.height;
    encodeAttr.params.width = imgInfo.output.width;
    encodeAttr.params.jpegQuality = 95;
    encodeAttr.params.inputFormat = imgInfo.output.outputFmt;
    encodeAttr.input = image;
    encodeAttr.output.size = image.size;
    lynMalloc((void **)&encodeAttr.output.data, image.size);
    lynJpegEncodeAsync(stream, &encodeAttr);
    lynSynchronizeStream(stream);
    uint32_t encodeSize = 0;
    lynEncGetRemotePacketValidSize(&encodeAttr.output, &encodeSize);
    uint8_t *hostBuf = new uint8_t[encodeSize];
    lynMemcpy(hostBuf, encodeAttr.output.data, encodeSize, ServerToClient);
    std::ofstream outputfile;
    outputfile.open(outputPath, std::ios::binary | std::ios::out);
    outputfile.write((char *)hostBuf, encodeSize);
    outputfile.close();
    delete[] hostBuf;
    lynFree(encodeAttr.output.data);
  }
};